/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package m12cqis01.nhathv.parser;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import m12cqis01.nhathv.util.RegexUtil;
import m12cqis01.nhathv.vo.GGItemVO;
import m12cqis01.nhathv.vo.ProductVO;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author NhatHV
 */
public class GGResponeParser {

    /**
     * Get Data
     *
     * @param response
     * @return GGItemVO
     */
    public ArrayList<GGItemVO> parseData(String response) {
        if (response == null){
            return null;
        }
        
        JSONObject jSONObject = new JSONObject();
        JSONParser jsonParser = new JSONParser();

        try {
            jSONObject = (JSONObject) jsonParser.parse(response);

        } catch (ParseException ex) {
            Logger.getLogger(GGResponeParser.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (jSONObject.containsKey("queries")) {
            JSONObject queriesJsonObj = (JSONObject) jSONObject.get("queries");
            if (queriesJsonObj.containsKey("request")) {
                JSONArray requestsJsonObj = (JSONArray) queriesJsonObj.get("request");
                JSONObject requestJsonObj = (JSONObject) requestsJsonObj.get(0);
                if (requestJsonObj.containsKey("totalResults")) {
                    String totalResults = (String) requestJsonObj.get("totalResults");
                    System.out.println("parseData, totalResults: " + totalResults);
                }
            }

        }

        // get items
        if (jSONObject.containsKey("items")) {
            JSONArray itemsArray = (JSONArray) jSONObject.get("items");
            System.out.println("parseData, Items size = " + itemsArray.size());
            ArrayList<GGItemVO> ggItems = new ArrayList<>();
            for (int i = 0; i < itemsArray.size(); i++) {
                JSONObject itemObj = (JSONObject) itemsArray.get(i);
                GGItemVO ggItemVO = new GGItemVO();

                // get title
                if (itemObj.containsKey("title")) {
                    String title = (String) itemObj.get("title");
                    ggItemVO.setTitle(title.replaceAll(RegexUtil.USELESS_CHAR, "").toLowerCase());
                }
                // get snippet
                if (itemObj.containsKey("snippet")) {
                    String snippet = (String) itemObj.get("snippet");
                    ggItemVO.setSnippet(snippet.replaceAll("\t", "").replaceAll("\n", "").toLowerCase().trim());
                }
                // get link
                if (itemObj.containsKey("link")) {
                    String link = (String) itemObj.get("link");
                    ggItemVO.setLink(link);
                }
                // get price
                if (itemObj.containsKey("pagemap")) {
                    JSONObject pagemapObj = (JSONObject) itemObj.get("pagemap");
                    if (pagemapObj.containsKey("offer")) {
                        JSONArray offerArray = (JSONArray) pagemapObj.get("offer");
                        if (offerArray.size() > 0) {
                            ArrayList<String> offers = new ArrayList<String>();
                            for (int offerNo = 0; offerNo < offerArray.size(); offerNo++) {
                                JSONObject offerObj = (JSONObject) offerArray.get(offerNo);
                                if (offerObj.containsKey("price")) {
                                    String price = (String) offerObj.get("price");
                                    offers.add(price);
                                }
                            }
                            ggItemVO.setOffers(offers);
                        }
                    }
                }
                /*
                 * https://www.googleapis.com/customsearch/v1?key=AIzaSyA_3w1yq-X3MdCH6HL2lwiNbwgkMzR3Ao4&cx=013036536707430787589:_pqjad5hr1a&num=10&alt=json&start=1&q=T%E1%BB%A7+l%E1%BA%A1nh+Samsung+RT29FARBDP2
                 */
                // get product
                if (itemObj.containsKey("pagemap")) {
                    JSONObject pagemapObj = (JSONObject) itemObj.get("pagemap");
                    if (pagemapObj.containsKey("product")) {
                        JSONArray productArray = (JSONArray) pagemapObj.get("product");
                        if (productArray.size() > 0) {
                            ArrayList<ProductVO> products = new ArrayList<ProductVO>();
                            for (int productNo = 0; productNo < productArray.size(); productNo++) {
                                JSONObject productObj = (JSONObject) productArray.get(productNo);
                                ProductVO product = new ProductVO();
                                if (productObj.containsKey("name")) {
                                    String name = (String) productObj.get("name");
                                    product.setName(name.replaceAll(RegexUtil.USELESS_CHAR, "").toLowerCase());
                                }

                                if (productObj.containsKey("image")) {
                                    String image = (String) productObj.get("image");
                                    product.setImage(image);
                                }

                                if (productObj.containsKey("description")) {
                                    String description = (String) productObj.get("description");
                                    product.setDescription(description);
                                }
                                if (productObj.containsKey("price")) {
                                    String price = (String) productObj.get("price");
                                    product.setPrice(price);
                                }

                                products.add(product);
                            }
                            ggItemVO.setProducts(products);
                        }
                    }
                }

                // add to list
                ggItems.add(ggItemVO);

            }

            return ggItems;
        } else {
            return null;
        }
    }
}
